<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Drop Demo</title>
    <style>
      #output {
        padding: 10px;
      }
      #output > div {
        padding: 0 10px 0 30px;
        background-repeat: no-repeat;
        background-position: 8px 5px;
        /* border-bottom: 1px solid #ccc; */
      }
      .directory {
        background-image: url();
      }
      .file {
        background-image: url();
      }
    </style>
  </head>
  <body>
    <div><button>选择目录</button> 或 拖放文件到窗口</div>
    <div id="output"></div>
    <input type="file" nwdirectory nwdirectorydesc="选择目录" style="display: none" />
    <script>
      const fs = require("node:fs");
      const path = require("node:path");

      // 文件排序
      function sortFiles(files) {
        return files
          .map((file) => {
            file.isDirectory = fs.statSync(file.path).isDirectory();
            return file;
          })
          .sort(
            (a, b) =>
              // 文件夹在前
              b.isDirectory - a.isDirectory ||
              // 文件名排序（含数值比较，如"2.*"会排在"10.*"前面）
              a.path.localeCompare(b.path, undefined, { numeric: true })
          );
      }

      function output(files) {
        document.querySelector("#output").innerHTML = files
          .map(
            (file) =>
              `<div
                class="${fs.statSync(file.path).isDirectory() ? "directory" : "file"}"
                title="${file.path}"
              >${file.name}</div>`
          )
          .join("");
      }

      // 拖放
      const preventDefault = (e) => {
        e.preventDefault();
        e.stopPropagation();
        return false;
      };
      window.addEventListener("dragenter", preventDefault);
      window.addEventListener("dragover", preventDefault);
      window.addEventListener("dragleave", preventDefault);
      window.addEventListener("drop", preventDefault);
      window.addEventListener("drop", (e) => {
        const files = sortFiles([...e.dataTransfer.files]);
        console.log(files);
        output(files);
      });

      // 读取文件夹
      const $input = document.querySelector("input");
      $input.onchange = () => {
        const dir = $input.value;
        let files = fs.readdirSync(dir).map((name) => {
          return {
            path: path.join(dir, name),
            name,
          };
        });
        files = sortFiles(files);
        console.log(files);
        output(files);
        $input.value = "";
      };
      document.querySelector("button").onclick = () => $input.click();
    </script>
  </body>
</html>
